<!--suppress ALL -->
<template>
  <div style="background-color: #5c6b77;height: 100%; ">
    <div style="height: 100%; width: 10%;float: left; ">
      <div style=" backgroundColor: darkgreen; height: 100%; width: 100%; ">
        <el-scrollbar style="height: 85%;background-color: #D3DCE6; position: relative;">
          <ul v-for="(item) in chats">
            <li style="margin: 5px" @click="change(item)" :class='item.customB.id==selected.customB.id?"selected":""'>
            <span
              style="background-color: #D3DCE6;height: 90%; width:100%; display:inline-block; text-align-last: justify;">
              <span>
                <el-image
                  style="width: 100%; height: 100%;"
                  :src=item.customB.portrait
                  fit="fit">
                </el-image>
              </span>
              <div :class='item.online?"online":"offline"' style="border-radius: 100%;height: 10px; width: 10px;"></div>
              <span style="text-align: center; ">
                {{ item.customB.nickName }}
              </span>
              <span style="">
              <el-button type="danger" icon="el-icon-delete" circle size="mini"
                         @click="deleteRelation(item.id)"></el-button>
              </span>
            </span>
            </li>
          </ul>
          <a-drawer
            placement="bottom"
            :closable="false"
            :visible="visible"
            :get-container="false"
            :wrap-style="{ position: 'absolute', }"
            :drawer-style="{backgroundColor: '#D3DCE6',}"
            :body-style="{ padding: '0px'}"
          >
            <ul v-for="(item) in users">
              <li @click="change1(item)" :class='item.id==userSelected?"selected":""'>
            <span style="background-color: #6eb6de;height: 100%; width:100%; display: inline-block;   font-size: 14px;">
              <div style="float: left; ">
                <el-image
                  style="width: 50px; height: 50px"
                  :src=item.portrait
                  fit="fit">
                </el-image>
              </div>
              {{ item.nickName }}
            </span>
              </li>
            </ul>
          </a-drawer>
        </el-scrollbar>

        <div
          style="height: 15%; width: 100%; background-color: darkgreen; font-size: 30px; text-align:center; line-height: 100px; "
          align="center" @click="showDrawer">
          发起会话
        </div>
      </div>
    </div>
    <div style="float: left; height: 100%;">
      <el-scrollbar ref="myScrollbar" class="triangle">
        <div v-if="flag">
          <ul v-for="(item) in messages">
            <span>{{ item.date }}</span>
            <li :class="item.style">
              <span>{{ item.content }}</span>
            </li>
          </ul>
        </div>
        <div v-if="!flag" style="margin: 10px; ">
          暂无数据
        </div>
      </el-scrollbar>
      <el-input
        @keyup.ctrl.enter.native="send"
        class="triangle1"
        type="textarea"
        :rows="4"
        placeholder="按 Ctrl + Enter 发送"
        v-model="currentMsg">
      </el-input>
    </div>
  </div>

</template>

<script>
import {del, get, post} from "../../../components/HttpUtil";
import {url, wsUrl} from "../../../common/Common";
import {formatDate} from "../../../common/DateUtil";


import Vue from "vue";

export default {
  name: 'MediaChatPage',
  data() {
    return {
      messages: [],
      currentMsg: "",
      userAllUrl: url.uaa.user.all,
      mediaChatMessageAddUrl: url.media.message.add,
      mediaChatMessageListUrl: url.media.message.list,
      mediaChatListUrl: url.media.chat.list,
      mediaChatAddUrl: url.media.chat.add,
      mediaChatDeleteUrl: url.media.chat.delete,
      mediaChatOnlineUrl: url.media.chat.online,

      chats: [],
      users: [],

      currentPage: 1,
      pageSize: 10,
      count: 0,
      flag: false,
      selected: -1,  //当前选中对话
      userSelected: -1, //添加对话关系时所选中人id
      visible: false,
    }
  },

  methods: {
    send() {
      if (this.selected.id == -1) {
        Vue.prototype.$message.error("对话未选中")
        return;
      }

      this.messages.push({
        style: "textRight",
        content: this.currentMsg,
        date: formatDate(new Date())
      });

      var content = {
        type: 1,
        content: this.currentMsg,
        chat: {"id": this.selected.id},
        userFrom: {"id": this.$store.state.loginData[1].id},
        userTo: {"id": this.selected.customB.id}
      }
      post(this.mediaChatMessageAddUrl, this.$store.state.token, content, false)
        .then(res => {
          this.currentMsg = "";

        })
        .catch(e => {
          console.log(e)
        })
    },
    gainChatList() {
      this.chats = [];
      get(this.mediaChatListUrl + '?size=' + this.pageSize + '&page=' + this.currentPage, this.$store.state.token)
        .then(res => {
          var id = this.$store.state.loginData[1].id;
          var contents = res.data.contents
          for (var i = 0; i < contents.length; i++) {
            if (contents[i].customA.id != id) {
              this.chats.push(contents[i])
            }
            if (contents[i].customB.id != id) {
              this.chats.push(contents[i])
            }
          }
          console.log(this.chats)
          this.onlineMsg();
          this.selected = this.chats[0]
        })
        .catch(e => {
          console.error(e)
        })
    },
    gainMessageList() {
      this.messages = [];
      get(this.mediaChatMessageListUrl + this.selected.id + '?size=' + this.pageSize + '&page=' + this.currentPage, this.$store.state.token)
        .then(res => {
          this.messages = res.data.contents;
          if (this.messages.length > 0) {
            this.flag = true;
          }
          for (var i = 0; i < this.messages.length; i++) {
            this.messages[i].date = formatDate(new Date(this.messages[i].date))
            if (this.$store.state.loginData[1].id == this.messages[i].userFrom.id) {
              this.messages[i].style = "textRight";
              console.log(this.messages[i].style)
            }
            if (this.$store.state.loginData[1].id == this.messages[i].userTo.id) {
              this.messages[i].style = "textLeft";
              console.log(this.messages[i].style)
            }
          }
          this.message = this.messages.reverse();
        })
        .catch(e => {
          console.error(e)
        })
    },
    change(item) {
      console.log(item)
      this.selected = item;
      this.gainMessageList();
    },
    change1(item) {
      this.userSelected = item.id;
      if (this.userSelected == this.$store.state.loginData[1].id) {
        Vue.prototype.$message.error("和自己对话可不是个正常人该干的事")
        return;
      }
      this.$confirm('打个招呼嘛？')
        .then(_ => {
          var data = {'customA': {'id': this.$store.state.loginData[1].id}, 'customB': {'id': this.userSelected}};
          post(this.mediaChatAddUrl, this.$store.state.token, data)
            .then(res => {
              this.visible = !this.visible;
              this.gainChatList();
              this.selected = res.data;
              this.gainMessageList();
            })
            .catch(e => {
              console.log(e)
            })
        })
        .catch(_ => {
        })
    },
    showDrawer() {
      this.gainUsers();
      this.visible = !this.visible;
    },
    gainUsers() {
      get(this.userAllUrl, this.$store.state.token)
        .then(res => {
          this.users = res.data
        })
        .catch(e => {
          console.error(e)
        })
    },
    deleteRelation(val) {
      this.$confirm('确认删除对话吗？')
        .then(_ => {
          del(this.mediaChatDeleteUrl + '?ids=' + val, this.$store.state.token)
            .then(res => {
              this.gainChatList()
            })
            .catch(e => {
              console.error(e)
            })
        })
        .catch(_ => {
        })
    },
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持WebSocket");
        return false;
      }
      const wsuri = wsUrl + this.$store.state.token

      this.websock = new WebSocket(wsuri);
      this.websock.onopen = this.websocketonopen;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //连接成功
    websocketonopen() {
      console.log("WebSocket连接成功");
      // 添加心跳检测，每30秒发一次数据，防止连接断开（这跟服务器的设置有关，如果服务器没有设置每隔多长时间不发消息断开，可以不进行心跳设置）
      let self = this;
      this.timer = setInterval(() => {
        try {
          self.websock.send('test')
          console.log('发送消息');
        } catch (err) {
          console.log('断开了：' + err);
          self.connection()
        }
      }, 3000000)
    },
    //接收后端返回的数据，可以根据需要进行处理
    websocketonmessage(e) {
      let message = JSON.parse(e.data);
      console.log(message)
      this.chats.forEach((e) => {
        if (e.customB.id == message.userFrom.id) {
          switch (message.type) {
            case 1:
              var content = {
                "userFrom": message.userFrom,
                "userTo":
                  {
                    "id": e.customA.id
                  },
                "chat":
                  {
                    "id": e.id
                  },
                "type": message.type,
                "content": message.content,
                "date": message.date,
                "receive": true,
              }
              post(this.mediaChatMessageAddUrl, this.$store.state.token, content)
                .then(res => {
                  this.messages.push({
                    style: "textLeft",
                    content: content.content,
                    date: formatDate(new Date())
                  });
                })
                .catch(e => {
                  console.log(e)
                });
              break;
            case 10:
              e.online = true;
              var ids = [message.userFrom.id]
              post(this.mediaChatOnlineUrl + "?type=11", this.$store.state.token, ids);
              break;
            case 11:
              e.online = true;
              break;
            case 12:
              e.online = false;
              break;
            case 13:

              break;
          }
        }
      })

    },
    //连接建立失败重连
    websocketonerror(e) {
      console.log(`连接失败的信息：`, e);
      this.initWebSocket(); // 连接失败后尝试重新连接
    },
    //关闭连接
    websocketclose(e) {
      console.log("断开连接", e);
    },
    scrollDown() {
      this.$nextTick(() => {
        this.$refs["myScrollbar"].wrap.scrollTop = this.$refs["myScrollbar"].wrap.scrollHeight;
      })
    },
    onlineMsg() {
      var ids = []
      for (var i = 0; i < this.chats.length; i++) {
        ids.push(this.chats[i].customB.id)
      }
      post(this.mediaChatOnlineUrl + "?type=10", this.$store.state.token, ids)
    },
    offlineMsg() {
      var ids = []
      for (var i = 0; i < this.chats.length; i++) {
        ids.push(this.chats[i].customB.id)
      }
      post(this.mediaChatOnlineUrl + "?type=12", this.$store.state.token, ids)
    },


  },
  created: function () {
    this.gainChatList()
    if (this.websock) {
      this.websock.close(); // 关闭websocket连接
    }
    this.initWebSocket();

  },
  destroyed() {
    //页面销毁时关闭ws连接
    if (this.websock) {
      this.websock.close(); // 关闭websocket
    }
    this.offlineMsg()
  },
  updated() {
    this.scrollDown();

  }
}
</script>

<style type="text/css">
.el-scrollbar__wrap {
  overflow: scroll;
  height: 100% !important;
  overflow-x: hidden !important;
}

* {
  margin: 0;
  padding: 0;
}

body {
  font-size: 14px;
}

.triangle {
  width: 500px;
  height: 85%;
  margin: 0 auto;
  background-color: #f5f5f5;
}

.triangle1 {
  width: 500px;
  height: 15%;
  margin: 0 auto;
  text-align: left;
  background-color: #ffffff;
}

.triangle ul {
  padding: 10px;
}

.triangle li {
  padding: 5px;
  margin-bottom: 10px;
}

.triangle li span {
  position: relative;
  border-radius: 7px;
  background-color: #a6e860;
  padding: 6px 10px 8px 10px;
  z-index: 1;
  height: 100%;
  display: inline-block;
  word-wrap: break-word;
}

.triangle .textLeft span {
  background-color: white;
  float: left;
  height: 100%;
  display: inline-table;
}

.triangle li.textLeft:before {
  box-sizing: border-box;
  position: relative;
  left: -10px;
  top: 9px;
}

.triangle li.textLeft span:before {
  content: "";
  display: block;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-right: 8px solid white;
  position: absolute;
  top: 8px;
  left: -16px;
}

.triangle li.textRight:after {
  box-sizing: border-box;
  position: relative;
  right: -10px;
  top: 9px;
}

.triangle li.textRight span:after {
  content: "";
  display: block;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-left: 8px solid #a6e860;
  position: absolute;
  top: 8px;
  right: -16px;
}

li {
  list-style: none;
}

.textRight {
  text-align: right;
}

.selected {
  border: 4px solid transparent;
  background-color: #FFFFFF;
}

.online {
  background-color: limegreen;
}

.offline {
  background-color: grey;
}

</style>
